define(function(require){
    $(function(){
    	/*------------------------------ 媒体库 ------------------------------*/

        /* 表格 */
    	 var bodyTemplate =
             '<tr>'
         	 + '<td class="txtc" media_id="{id}">{media_name}</td>'
         	 + '<td class="txtc">{media_attrs}</td>'
             + '<td class="txtc"><a class="ibtn showchart" href="javascript:;">报表</a><a class="ibtn showmedia" href="javascript:;">查看</a><a class="ibtn delmedia" href="javascript:;">删除</a></td>'
             + '</tr>';
        
        var pageTemplate =
            '<div class="gridTotal">共<b>{totalCount}</b>个广告活动</div>' +
            '<input type="button" value="首页" class="page-bt first-page" title="首页">' +
            '<input type="button" value="上一页" class="page-bt pre-page" title="上一页">' +
            '第{pageNo}页' +
            '<input type="button" value="下一页" class="page-bt next-page" title="下一页">' +
            '<input type="button" value="末页" class="page-bt last-page" title="末页">' +
            '共{totalPage}页&nbsp;&nbsp;跳转至' +
            '<input type="text" size="4" maxlength="5" class="some-page"/>' +
            '每页<select class="page-size"><option value="10">10</option><option value="20">20</option></select>条记录';
        
        var date = $('[name=reservation]').val().split(' 至 ');
	    var grid = Grid.init({
	            holder:'mediaResources',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/media_list/',
	            pageTemplate:pageTemplate
	        });
        grid.send({
    		search_text: '',
    		start: date[0],		//必填
    		end: date[1],		//必填
    		orderBy: '',
    		pageSize: 20,
    		pageNo: 1
    	});
        
        /* 数据筛选 */
        var filterData = function(){
        	var txt = $('.searchbox-ipt').val(),
            	date = $('[name=reservation]').val().split(' 至 ');
            grid.send({
        		search_text: txt,
        		start: date[0],
        		end: date[1],
        		orderBy: '',
        		pageSize: 20,
        		pageNo: 1
        	});
        };
        
        /* 日期选择 */
        $('input[name=reservation]').daterangepicker({
            format:'YYYY-MM-DD'
        }, function(start, end, label) {
        	console.log(start.toISOString(), end.toISOString(), label);
        	filterData();
        });
        
        /* 搜索 */
        $('.searchbox-btn').click(function(){
            if(semi.utils.isEmpty($('.searchbox-ipt').val()))return;
            filterData();
        });
        
        /* 报表——弹框 */
        
        /* 查看——弹框 */
        $(document).on('click', '.showmedia', function(){
        	var $dlg = $dialog({
                title: '媒体详情',
                content: $('.pop-showmedia').clone().show()[0],
                button: [
                     {
                         value: '修改',
                         callback: function(){
                        	 this.button([
          	                     {
        	                         value: '确定',
        	                         callback: function(){
        	                        	 
        	                         }
        	                     },
        	                     {
        	                         value: '取消'
        	                     }
        	                 ]);
                        	 var $pop = $('.pop-showmedia');
                        	 $('.media_name,.media_attrs,.channel_name,.channel_attrs',$pop).hide().siblings('.form-control').show();
                        	 return false;
                         }
                     },
                     {
                         value: '取消'
                     }
                 ]
            }).showModal();
        	
        });
        
        /* 新增媒体 */
        
       $('.createmedia').on('click', function(){
        	var $dlg = $dialog({
                title: '新增媒体',
                content: $('.pop-showmedia').clone().show()[0],
                button: [{
                	value: '创建',
                	callback: function(){
                		var $cont = $(this.node),
                			m_name = $('[name=media_name]',$cont).val(),
                			m_attrs = $('[name=media_attrs]',$cont).val(),
                			channels = [];
                		
                		if(semi.utils.isEmpty(m_name)){
                			return;
                		}
                		if(semi.utils.isEmpty(m_attrs)){
                			return;
                		}
                		$('tbody tr',$cont).each(function(){
                			var $tr = $(this), c_name = $('[name=channel_name]',$tr).val(), c_attrs = $('[name=channel_attrs]',$tr).val();
                			if(semi.utils.isEmpty(c_name) || semi.utils.isEmpty(c_attrs))return;
                			channels.push({
                				channel_name: c_name,
                				channel_attrs: c_attrs
                			})
                		});
                		
                    	$ajax.ajax({
                        	url : '/trp/media/create/',
                            data : JSON.stringify({
                        		media_name: m_name,
                        		media_attrs: m_attrs,
                        		channels: channels
            				}),
                            contentType : "application/json",
                            type : 'POST',
                            dataType : 'json',
                            success: function(){
                            	$dlg.close();
                            }
                        });
                    	//return false;  TODO
                    },
                    autofocus: true
                },{
                	value: '取消'
                }]
            }).showModal();
        	
        });
        
        var channelTmepl = ['<select name="channel_attrs" class="form-control">',
					        	'<option>1</option>',
					        	'<option>2</option>',
					        	'<option>3</option>',
					        	'<option>4</option>',
					        	'<option>5</option>',
					        '</select>'].join('');
        $(document).on('click', '.pop-showmedia .delchannel', function(){
			$(this).parents('tr:first').remove();
		});
        $(document).on('click', '.pop-showmedia .addchannel', function(){
			$(this).parents('table:first').find('tbody').append('<tr><td class="txtc"><input type="text" name="channel_name" class="form-control" placeholder="请输入"/></td>'+
			                                                     '<td class="txtc">'+channelTmepl+
			                                                     '<a class="glyphicon glyphicon-minus delchannel" href="javascript:;" title="删除频道"></a></td></tr>');
		});
        
        /* 删除——弹框 */
        
        
        
       /* $('.createmedia').on('click', function(){
        	var $dlg = $dialog({
                title: '修改媒体',
                content: $('.pop-showmedia').clone().show()[0],
                button: [{
                	value: '修改',
                	callback: function(){
                    	$ajax.ajax({
                        	url : '/trp/media/update/',
                            data : JSON.stringify({
                            	media_id: '7'
                        		media_name: '李博龙12',
                        		media_attrs: '1',
                        		channels: [
                				        {
                				        	channel_id: '1',
                				        	channel_name: '频道名称1',
                				        	channel_attrs: '1'
                				        },
                				        {
                				        	channel_id: '2',
                				        	channel_name: '频道名称2',
                				        	channel_attrs: '2'
                				        },
                				        {
                				        	channel_name: '频道名称4',
                				        	channel_attrs: '3',
                				        	channel_id: '-1'
                				        }
                				   ]
                				}),
                            contentType : "application/json",
                            type : 'POST',
                            dataType : 'json',
                            success: function(){
                            	$dlg.close();
                            }
                        });
                    	return false;
                    },
                    autofocus: true
                },{
                	value: '取消'
                }],
                onshow: function(){
                	
                }
            }).showModal();
        	
        });*/
        
    });
});